import { userManage } from '../api';

export default {
  namespace: 'userManage',
  state: {
    data: {},
    isList: {},
    userData: {},
    queryUserMsg: false
  },
  reducers: {
    querySuccess(state, { payload }) {
      return {
        ...state,
        ...payload
      };
    }
  },
  effects: {
    * queryList({ payload: params }, { call, put }) {
      const { jsonResult } = yield call(userManage.queryList, params );
      yield put({
        type: 'querySuccess',
        payload: {
          data: jsonResult.data
        }
      });
    },
    * isList({ payload: params }, { call, put }) {
      const { jsonResult } = yield call(userManage.queryList, params );
      yield put({
        type: 'querySuccess',
        payload: {
          isList: jsonResult.data
        }
      });
    },
    * addUser({ payload: {  params, func } }, { call, put }) {
      const { jsonResult } = yield call(userManage.addUser, params);
      if (typeof func === 'function') {
        func();
      }
    },
    * queryUser({ payload: {  id, userId} }, { call, put }) {
      const { jsonResult } = yield call(userManage.queryUser, {  id,userId });
      yield put({
        type: 'querySuccess',
        payload: {
          queryUserMsg: jsonResult.data
        }
      });
    },
    * userUpdate({ payload: {  params, func } }, { call, put }) {
      const { jsonResult } = yield call(userManage.queryUpdate, params);
      if (typeof func === 'function') {
        func();
      }
      // yield put({
      //   type: 'querySuccess',
      //   payload: {
      //     queryUserMsg: jsonResult.data
      //   }
      // });
    },
    * bangUserRole({ payload: {  params, func } }, { call, put }) {
      const { jsonResult } = yield call(userManage.bangUserRole, params);
      if (typeof func === 'function') {
        func();
      }
      // yield put({
      //   type: 'querySuccess',
      //   payload: {
      //     queryUserMsg: jsonResult.data
      //   }
      // });
    },
    * remove({ payload: id }, { call, put }) {
      yield call(service.remove, id);
      yield put({ type: 'reload' });
    },
    * save({ payload: params }, { call, put }) {
      yield put({
        type: 'querySuccess',
        payload: {
          userData: params
        }
    });
    },
    * reload(action, { put, select }) {
      const page = yield select(state => state.users.page);
      yield put({ type: 'fetch', payload: { page } });
    }
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, query }) => {
        if (pathname === '/services') {
          dispatch({ type: 'fetch', payload: query });
        }
      });
    }
  }
};
